package demo

import (
	"errors"
	"gim-server/consts"
	"gim-server/errs"
	"gim-server/model"
	"gim-server/sdk"
	"gim-server/utils"
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

type EditProfileArgs struct {
	Nickname string `json:"nickname"`
	Avatar   string `json:"avatar"`
	Gender   int    `json:"gender"`
	RegStep  int    `json:"reg_step"`
}

func editProfile(ctx *gin.Context) {
	var (
		err  error
		args = new(EditProfileArgs)
	)
	if err = ctx.ShouldBindJSON(args); err != nil {
		utils.ERR(ctx, &utils.ErrArgs{
			Code: errs.ApiParamsErr,
			Err:  err,
		})
		return
	}
	db := sdk.DB(ctx)
	user := new(model.TbUserDemo)
	err = db.First(user, "uid = ?", ctx.GetString(consts.UID)).Error
	if err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			utils.ERR(ctx, &utils.ErrArgs{
				Code: errs.ApiRecordNotFound,
				Err:  err,
			})
			return
		} else {
			utils.ERR(ctx, &utils.ErrArgs{
				Code: errs.ApiDbErr,
				Err:  err,
			})
			return
		}
	}
	if args.Nickname != "" {
		user.Nickname = args.Nickname
	}
	if args.Avatar != "" {
		user.Avatar = args.Avatar
	}
	if args.Gender == 1 || args.Gender == 2 {
		user.Gender = args.Gender
	}
	if args.RegStep > 0 {
		user.RegStep = args.RegStep
	}
	if err = db.Save(user).Error; err != nil {
		utils.ERR(ctx, &utils.ErrArgs{
			Code: errs.ApiDbErr,
			Err:  err,
		})
		return
	}
	utils.SUC(ctx, user)
}
